
<script lang="ts" setup>
const htmlAttrs = ref()

const changeTheme = () => {
  const currentTheme = document.documentElement.getAttribute('data-theme')
  const newTheme = currentTheme === 'dark' ? 'light' : 'dark'
  // document.documentElement.setAttribute('data-theme', newTheme)
  htmlAttrs.value = currentTheme
  useHead({
    htmlAttrs: {
      'data-theme': newTheme  
    }
  })
}

onMounted(() => {
  htmlAttrs.value = document.documentElement.getAttribute('data-theme')
})

/** Nuxt UI 会自动注册@nuxtjs/color-mode模块，无需额外设置。您只需使用 useColorMode 可组合函数即可在亮色和暗色模式之间切换
    可以通过在 nuxt.config.ts 文件中使用 
    ui: {
      colorMode: false
    }
    选项来禁用 @nuxtjs/color-mode 模块
 * 
 */

const colorMode = useColorMode()

const isDark = computed({
  get() {
    return colorMode.value === 'dark'
  },
  set(_isDark) {
    colorMode.preference = _isDark ? 'dark' : 'light'
  }
})

// 定义快捷键，尝试按键盘的B或L
defineShortcuts({
  b: () => {
    isDark.value = true
  },
  l: () => {
    isDark.value = false
  }
})
</script>

<template>
  <div>
    <h1>Change Theme</h1>
    <div>自定义切换主题</div>
    <UButton @click="changeTheme">Change Theme:{{ htmlAttrs }}</UButton>
    <div>NuxtUI切换主题(尝试按键盘的B或L切换主题)</div>
    <ClientOnly v-if="!colorMode?.forced">
      <UButton
        :icon="isDark ? 'i-lucide-moon' : 'i-lucide-sun'"
        color="neutral"
        variant="ghost"
        @click="isDark = !isDark"
      />

      <template #fallback>
        <div class="size-8" />
      </template>
    </ClientOnly>
  </div>
</template>

<style lang="scss" scoped>
@use "~/assets/css/my-theme.scss" as Theme;

h1 {
  @include Theme.useTheme {
    background-color: Theme.getVar('primary-color');
    color: Theme.getVar('text-color');

    &:hover {
      background-color: Theme.getVar('hover-color');
    }
  }
}
</style>